package com.chj.setQueue;

import com.chj.testmq.TestProducer;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 控制队列的参数
 * x-dead-letter-exchange：死信交换器x-dead-letter-routing-key 死信消息的可选路由键
 * x-expires：队列在指定毫秒数后被删除
 * x-ha-policy：创建 HA 队列
 * x-ha-nodes：HA队列的分布节点
 * x-max-length：队列的最大消息数
 * x-message-ttl：毫秒为单位的消息过期时间，队列级别
 * x-max-priority：最大优先值为 255 的队列优先排序功能
 */
public class SetQueueConsumer {
    public static void main(String[] argv)throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 打开连接和创建频道，与发送端一样
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare(TestProducer.EXCHANGE_NAME,"direct");

        //TODO 自动过期队列--参数需要Map传递
        String queueName = "setQueue";
        Map<String, Object> arguments = new HashMap<String, Object>();
        // TODO 队列在超过一段时间内没使用会被删除，单位毫秒
        arguments.put("x-expires",10*1000);//10秒被删除
        // TODO 设定该队列所有消息的存活时间，单位毫秒
        arguments.put("x-message-ttl",20*1000);//10秒被删除
        // TODO 队列参数：String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        // TODO 设置为自动删除 autoDelete = true
        channel.queueDeclare(queueName,false,false, true,arguments);
        // TODO 设置为单消费者队列(独占队列) exclusive为true
        channel.queueDeclare(queueName,false,true, false,arguments);
        // TODO 设置为自动删除 autoDelete = true
        channel.queueDeclare(queueName,false,false, true,arguments);
        //TODO 设置为自动过期队列
        channel.queueDeclare(queueName,true,true, false,arguments);

        // 绑定，将队列和交换器通过路由键进行绑定
        String routekey = "error";/*表示只关注error级别的日志消息*/
        channel.queueBind(queueName,TestProducer.EXCHANGE_NAME,routekey);
        System.out.println("waiting for message........");
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Received["+envelope.getRoutingKey() +"]"+message);
            }
        };
        // 消费者正式开始在指定队列上消费消息
        channel.basicConsume(queueName,true,consumer);
    }
}
